'use strict';
const unipay = require('uni-pay')
// wx-server-sdk
const md5 = require('md5')

const orderMapping = {
	'wx52d48be4d68f58a2': {
		mchId: '1628245715',
		key: '412728199807303111GYG07303111111'
	},
	'wx539417d2ef62a92c': {
		mchId: '1634582769'
	}
}

const defaulyAppid = 'wx52d48be4d68f58a2'

exports.main = async (event, context) => {
	console.log(event)

	const body = event.body ? JSON.parse(event.body) : event

	const appid = body.appId || defaulyAppid

	let orderInfo
	if (orderMapping[appid].key) {
		const unipayInit = unipay.initWeixin({
			"appId": appid, // 小程序的appid
			// "secret": "e1e5894c7b5a4e005f84737be6b8ee31", // 小程序的secret
			"mchId": orderMapping[appid].mchId, // 商户id
			"key": orderMapping[appid].key,
		})
		orderInfo = await unipayInit.getOrderInfo({
			openid: body.openid, //这个是客户端上传的用户的openid
			body: '测试支付费用', //商品描述
			outTradeNo: md5(
				`${body.id}${Date.now()}${Math.random().toString().slice(2)}`), //给他个随机号让他可以第二次发起支付
			totalFee: 1, // 金额分
			// 支付结果通知地址,没有该参数或者为空会报错,随便给了一个测试网址
			notifyUrl: "https://fc-mp-a2b27382-6a7c-4e2d-910d-dda497777459.next.bspapp.com/uni-pay-co",
		})
	} else {
		const payRes = await uniCloud.callFunction({
			name: 'orderpay',
			data: {
				openid: body.openid,
				id: '1231231231',
				appid,
				mchid: orderMapping[appid].mchId,
				out_trade_no: md5(`${body.id}${Date.now()}${Math.random().toString().slice(2)}`),
				total: 1,
				description: '测试支付费用',
				notify_url: "https://fc-mp-a2b27382-6a7c-4e2d-910d-dda497777459.next.bspapp.com/uni-pay-co"
			}
		})
		orderInfo = payRes.result
	}
	return {
		code: 200,
		msg: '获取订单信息成功',
		data: orderInfo
	}
};